package com.tedu.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class DBUitl {
    private static SqlSession session;
    private static SqlSessionFactory createSqlSessionFactory() {
        String path = "mybatis-config.xml";
        //加载MyBatis配置文件
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new SqlSessionFactoryBuilder().build(inputStream);
    }
    public static SqlSession openSession() {
        if(session == null) {
            session = createSqlSessionFactory().openSession();
        }
        return session;
    }

    public static void close(SqlSession session) {
        if(session != null) {
            session.close();
        }
    }
    public static void rollback(SqlSession session) {
        if(session != null) {
            session.rollback();
        }
    }
}
